﻿//---------------------------------------------------------------------------------------------
//  Copyright 2010 Jeremy Palenchar
//  http://identitynotes.palenchar.net
//
//  This file is part of the Identity Notes Sample Custom Activity Library.
//
//  The Identity Notes Sample Custom Activity Library is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  The Identity Notes Sample Custom Activity Library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with The Identity Notes Sample Custom Activity Library.  If not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.Activities;
using Microsoft.IdentityManagement.WebUI.Controls;
using Microsoft.IdentityManagement.WebUI.Controls.Resources;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Reflection;
using System.Workflow.ComponentModel;

namespace IdentityNotes.Examples.CustomActivityLibrary
{


    public abstract class GenericSettingsPart : ActivitySettingsPart
    {



        const string ID_PREFIX = "id_";
        protected List<ConfigurationObject> _config;

        private Type activityType;

        public GenericSettingsPart() { }

        protected GenericSettingsPart(Type activityType)
        {
            this.activityType = activityType;
            _config = new List<ConfigurationObject>();
            
            //add default co for Activity Type
            _config.Add(new ConfigurationObject(ControlType.String,"ActivityName",24, 1, this.ClassName + "1"));
            
            //add co for each Property in the Activity with an ILM2UIAttribute
            foreach (PropertyInfo pi in activityType.GetProperties())
            {
                object[] attributes = pi.GetCustomAttributes(typeof(FIMActivityUIAttribute), false);
                foreach (Object attribute in attributes)
                {
                    FIMActivityUIAttribute uiAttrib = (FIMActivityUIAttribute)attribute;
                    _config.Add(new ConfigurationObject(ControlType.String,pi.Name,uiAttrib.Length,uiAttrib.Height,"<"+pi.Name+">"));
                }

            }

        }

        public override System.Workflow.ComponentModel.Activity GenerateActivityOnWorkflow(Microsoft.ResourceManagement.Workflow.Activities.SequentialWorkflow workflow)
        {
            if (!this.ValidateInputs())
            {
                return null;
            }

            Activity activity = (Activity)System.Activator.CreateInstance(activityType);

            foreach (ConfigurationObject config in _config)
            {
                if (this.activityType.GetProperty(config._lableName) != null //the activity contains the property
                    && this.GetControlString(config._lableName) != "") //the config part is not null
                {
                    PropertyInfo pi = this.activityType.GetProperty(config._lableName);

                    switch (pi.PropertyType.FullName)
                    {
                        case "System.Int32":
                            pi.SetValue(activity,int.Parse(this.GetControlString(config._lableName)),null);
                            break;
                        case "System.String":
                            pi.SetValue(activity, this.GetControlString(config._lableName), null);
                            break;
                        default:
                            throw new Exception("Cannot write configuration to unknown property type");
                    }
                }
                
            }

            
            activity.Name = this.GetControlString("ActivityName4");
            
            return activity;
        }

        public override void LoadActivitySettings(System.Workflow.ComponentModel.Activity activity)
        {
            foreach (ConfigurationObject config in _config)
            {
                if (this.activityType.GetProperty(config._lableName) != null)
                {
                PropertyInfo pi = this.activityType.GetProperty(config._lableName);
                this.SetTextBoxValue(config._lableName,System.Convert.ToString(pi.GetValue(activity, null)));
                }
            }
            this.SetTextBoxValue("ActivityName4", activity.Name);
        }

        public override ActivitySettingsPartData PersistSettings()
        {
            ActivitySettingsPartData data = new ActivitySettingsPartData();
            foreach (ConfigurationObject co in _config)
            {
                data[co._lableName] = GetControlString(co._lableName);
            }
            //data["ActivityName"] = GetControlString("ActivityName");
            return data;

        }

        public override void RestoreSettings(ActivitySettingsPartData data)
        {
            if (data != null)
            {
                foreach (ConfigurationObject co in _config)
                {
                    SetTextBoxValue(co._lableName, data[co._lableName] as string);
                }
            }
            //SetTextBoxValue("ActivityName", data["ActivityName"] as string);

        }

        public override void SwitchMode(ActivitySettingsPartMode mode)
        {
            bool flag = mode != ActivitySettingsPartMode.Edit;
            foreach (ConfigurationObject co in _config)
            {

                SetControlAccess(ID_PREFIX + co._lableName, flag);
            }

        }

        public override string Title
        {
            get 
            {
                return this.ClassName + ": " + this.GetControlString("ActivityName");
            }
        }

        private string ClassName
        {
            get
            {
                string[] nameTokens = this.activityType.ToString().Split('.');
                string className = nameTokens[nameTokens.Length - 1];
                return className;
            }
        }
        public override bool ValidateInputs()
        {
            return true;
        }

        protected override void CreateChildControls()
        {
            Table controlLayoutTable = new Table();
            controlLayoutTable.Width = Unit.Percentage(100.0);
            controlLayoutTable.BorderWidth = 0;
            controlLayoutTable.CellPadding = 2;
            //controlLayoutTable.CssClass = base.TableCssClass; //??

            foreach (ConfigurationObject co in _config)
            {
                controlLayoutTable.Rows.Add(CreateTableRow(co));
            }
            this.Controls.Add(controlLayoutTable);
            base.CreateChildControls();
        }

        private TableRow CreateTableRow(ConfigurationObject co)
        {
            //New Row
            TableRow tableRow = new TableRow();

            //Label Cell
            TableCell tableCell = new TableCell();
            Label label = new Label();
            label.Text = co._lableName;
            label.CssClass = base.LabelCssClass;
            tableCell.Controls.Add(label);
            tableRow.Cells.Add(tableCell);

            //Textbox Cell
            tableCell = new TableCell();
            TextBox textBox = new TextBox();
            textBox.ID = ID_PREFIX + co._lableName;
            textBox.MaxLength = co._fieldLength;
            textBox.TextMode = TextBoxMode.MultiLine;
            textBox.Rows = co._fieldRows;
            textBox.Text = co._defaultValue;
            textBox.CssClass = base.TextBoxCssClass;
            tableCell.Controls.Add(textBox);
            tableRow.Cells.Add(tableCell);

            return tableRow;
        }

        public string GetControlString(string labelName)
        {
            TextBox oText = (TextBox)this.FindControl(ID_PREFIX + labelName);
            if (oText != null)
                return oText.Text;
            else
                return "[TextBox '" + ID_PREFIX + labelName + "' Not Found]";
        }

        public void SetTextBoxValue(string labelName, string value)
        {
            TextBox oText = (TextBox)this.FindControl(ID_PREFIX + labelName);
            if (oText != null)
                oText.Text = value;
        }
        private void SetControlAccess(string controlID, Boolean readOnly)
        {
            TextBox oText = (TextBox)this.FindControl(controlID);
            if (oText != null)
                oText.ReadOnly = readOnly;
        }


    }
}